import 'package:flutter/cupertino.dart';
import 'package:flutter_yn_goods/config/app_routes.dart';
import 'package:flutter_yn_goods/pages/goods_info/model/model_comment_config.dart';
import 'package:flutter_yn_goods/pages/goods_info/comment_list/model/model_comment_list.dart';
import 'package:flutter_yn_goods/pages/goods_info/model/model_goods_info.dart';
import 'package:flutter_yn_goods/user/app_user_manager.dart';
import 'package:flutter_yn_goods/utils/http/http_export.dart';
import 'package:flutter_yn_goods/utils/loading/loading_utils.dart';
import 'package:flutter_yn_goods/utils/log/utils_log.dart';
import 'package:get/get.dart';

class GoodsInfoLogic extends GetxController {
  int id = Get.arguments['id'];

  Rx<ModelGoodsInfo> goodsInfoRx = Rx(ModelGoodsInfo());

  // 创建收藏状态响应式变量
  var isCollected = false.obs;

  // 评论相关数据
  Rx<ModelCommentConfig> commentConfigRx = Rx(ModelCommentConfig());
  RxList<ModelCommentList> commentListRx = RxList<ModelCommentList>([]);

  ScrollController scrollController = ScrollController();
  var appBarOpacity = 0.0.obs;

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
    getDataSource();
    getCommentConfig();
    getCommentList();
    scrollController.addListener(addScrollListener);
  }

  addScrollListener() {
    // clog(scrollController.position.pixels);
    double offset = scrollController.offset;
    if (offset <= 50) {
      // 小于等于 50 不处理
      if (appBarOpacity.value != 0.0) {
        appBarOpacity.value = 0;
        // setState(() => _appBarOpacity = 0.0);
      }
    } else if (offset > 50 && offset <= 150) {
      // 50~150 范围线性插值透明度
      double opacity = (offset - 50) / 100;

      appBarOpacity.value = opacity.clamp(0.0, 1.0);
    } else {
      // 超过 150 保持最大透明度
      if (appBarOpacity.value != 1.0) {
        appBarOpacity.value = 1.0;
      }
    }
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
    scrollController.removeListener(addScrollListener);
    scrollController.dispose();
  }

  getDataSource() async {
    HttpResponse response = await HttpManager().get(
        "${API.getGoodsInfo}$id?uid=${AppUserManager().uid}&type=${AppUserManager().isLeader() ? 'leader' : 'user'}",
        fromJson: ModelGoodsInfo.fromJson);
    if (response.isSuccess) {
      goodsInfoRx.value = response.data;
      // 更新收藏状态
      isCollected.value = goodsInfoRx.value.storeInfo?.userCollect ?? false;
    }
  }

  // 添加收藏
  Future<bool> addToCollect({bool isWant = false}) async {
    if (!AppUserManager().isLogin) {
      Get.toNamed(AppRoutes.login);
      return false;
    }

    Map<String, dynamic> params = {
      'id': goodsInfoRx.value.storeInfo?.id,
      'type': AppUserManager().isLeader() ? 'leader' : 'user',
      'uid': AppUserManager().uid,
      'relation_type': isWant ? 'want' : 'collect'
    };

    HttpResponse response = await HttpManager().post(
      'api/collect/add',
      params: params,
      uiType: HttpUIType.loadingAndToast,
    );
    if (response.isSuccess) {
      isCollected.value = true;
      if (isWant) {
        LoadingUtils.showToast('已发送数据通知商户');
      }
      return true;
    }
    return false;
  }

  // 取消收藏
  Future<bool> cancelCollect() async {
    if (!AppUserManager().isLogin) {
      Get.toNamed(AppRoutes.login);
      return false;
    }

    Map<String, dynamic> params = {
      'id': [goodsInfoRx.value.storeInfo?.id], // 数组形式传入
      'type': AppUserManager().isLeader() ? 'leader' : 'user',
      'uid': AppUserManager().uid,
    };

    HttpResponse response = await HttpManager().post(
      'api/collect/del',
      params: params,
      uiType: HttpUIType.loadingAndToast,
    );
    if (response.isSuccess) {
      isCollected.value = false;
      return true;
    }
    return false;
  }

  // 切换收藏状态
  Future<bool> toggleCollect() async {
    if (isCollected.value) {
      return await cancelCollect();
    } else {
      return await addToCollect();
    }
  }

  // 我想要/立即购买 跳转
  void buyNow() {
    addToCollect(isWant: true);

    // 添加您的立即购买/我想要逻辑
    // 这里可以添加跳转到订单页面或其他处理
  }

  // 获取评论配置
  getCommentConfig() async {
    HttpResponse response = await HttpManager().get(
      "api/reply/config/$id",
      fromJson: ModelCommentConfig.fromJson,
    );
    if (response.isSuccess) {
      commentConfigRx.value = response.data;
    }
  }

  // 获取评论列表
  getCommentList() async {
    HttpResponse response = await HttpManager().get(
      "api/reply/list/$id",
      params: {
        'page': 1,
        'limit': 2, // 只获取前2条评论
      },
      fromJson: ModelCommentList.fromJson,
    );
    if (response.isSuccess) {
      commentListRx.value = response.data;
      // ModelCommentList commentList = response.data;
      // commentList.list
      // if ( (commentList.list ??[]).isNotEmpty) {
      // commentListRx.value = commentList.list ?? [];
      // }
    }
  }
}
